new Vue({
    el: '#app',
    data() {
        const Pass_Word = (rule, value, callback) => {
            if (validatePassword(this.form.Pass_Word)) {
                callback(new Error(validatePassword(this.form.Pass_Word)));
            } else {
                callback();
            }
        }
        const User_Number = (rule, value, callback) => {
            if (!validatemobile(this.form.User_Number)) {
                callback(new Error('请输入有效手机号'));
            } else {
                callback();
            }
        }
        return {
            form: {
                ID_Number: '',
                ID_Name: '',
                ID_Front: '',
                ID_Back: '',
                Phone: '',
                Validity_EndDate: '',
                ID_Address: '',
                ProvinceNumber: '',
                CityNumber: '',
                CountyNumber: '',
                TownNumber: '',
                VillageNumber: '',
                value1: [],
                town: [],//市区
                value2: [],
            },
            land: [{
                Traceability_Land_SerialNumber: '',
                ID_Number: '',
                Land_Number: '',
                ProvinceNumber: '',
                CityNumber: '',
                CountyNumber: '',
                TownNumber: '',
                VillageNumber: '',
                Located: '',
                Planting_Area: '',
                Category_SerialNumber: '',
                Land_Certificate: '',
                value1: [],
                town: [],//市区
                value2: [],
            }],
            rules: {

            },
            iconLoading: false,
            city: [],//城市
            value: [],
            category: [],
            address: '',
            loading: true,
        }
    },
    mounted() {
        const ID_Number = sessionStorage.getItem("ID_Number")
        this.getData(ID_Number);
    },
    watch: {
        'form.ID_Number'(val) {
            this.land.forEach(item => {
                item.ID_Number = val
            })
        },
        'form.ID_Front'(Data) {
            if (!this.loading) {
                const that = this;
                that.iconLoading = true;
                $.ajax({
                    url: `${BASE_URL1}/parseIDCardAction`,
                    type: 'POST',
                    data: { Data },
                    success: function (Result) {
                        if (Result.Status == 'success') {
                            that.form.ID_Number = Result.ID_Number;
                            that.form.ID_Name = Result.name;
                            let reg = /.+?(省|市|自治区|自治州|县|区)/g;
                            let arr = Result.address.match(reg);
                            let obj1 = that.city.filter(i => i.children && i.children.some(x => x.label == arr[0]))[0];
                            let obj2 = obj1.children.filter(i => i.label == arr[0])[0]
                            let obj3 = obj2.children.filter(i => i.label == arr[1])[0]
                            let arr1 = [];
                            if (obj1) {
                                arr1 = [obj1.value]
                                if (obj2) {
                                    arr1 = [...arr1, obj2.value]
                                    if (obj3) {
                                        arr1 = [...arr1, obj3.value]
                                    }
                                }
                            }
                            that.form.value1 = arr1
                        }
                    },
                    complete: function () {
                        that.iconLoading = false;
                    },
                    dataType: "json"
                });
            }
        }
    },
    methods: {
        getData(ID_Number) {
            const that = this;
            $.ajax({
                url: absolutepath() + "utils/city.json",
                type: "GET",
                success: function (data) {
                    that.city = data
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_category',
                    Condition: "Row_Status = '0'",
                },
                success: function (Result) {
                    that.category = Result
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                type: 'POST',
                data: {
                    Data: 'business_traceability_farmer',
                    Condition: "Row_Status = '0' and ID_Number = '" + ID_Number + "'",
                },
                success: function (Result) {
                    if (Result.length == 1) {
                        Result[0].value1 = [Result[0].ProvinceNumber, Result[0].CityNumber, Result[0].CountyNumber];
                        Result[0].town = JSON.parse(Result[0].TownJSON);
                        Result[0].value2 = [Result[0].TownNumber, Result[0].VillageNumber];
                        that.form = Result[0];
                        that.loading = false
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                type: 'POST',
                data: {
                    Data: 'business_traceability_land',
                    Condition: "Row_Status = '0' and ID_Number = '" + ID_Number + "'",
                },
                success: function (Result) {
                    if (Result.length >= 1) {
                        Result.forEach(item => {
                            item.value1 = [item.ProvinceNumber, item.CityNumber, item.CountyNumber];
                            item.town = JSON.parse(item.TownJSON);
                            item.value2 = [item.TownNumber, item.VillageNumber];
                        })
                        that.land = Result;
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        changeCity(arr, row) {
            //初始化
            row.ProvinceNumber = '';
            row.CityNumber = '';
            row.CountyNumber = '';
            row.TownNumber = '';
            row.VillageNumber = '';
            row.value2 = [];
            row.town = [];
            if (arr.length > 0) {
                row.ProvinceNumber = arr[0];
                row.CityNumber = arr[1];
                row.CountyNumber = arr[2];
                $.ajax({
                    url: `${BASE_URL1}/getTownSelector?CountyNumber=${arr[2]}`,
                    type: 'GET',
                    success: function (Result) {
                        row.town = Result;
                    },
                    dataType: "json"
                });
            }
        },
        changeTown(arr, row) {
            row.TownNumber = arr[0] ? arr[0] : '';
            row.VillageNumber = arr[1] ? arr[1] : '';
        },
        add_land() {
            this.land.push({
                Traceability_Land_SerialNumber: '',
                ID_Number: this.form.ID_Number,
                Land_Number: '',
                ProvinceNumber: '',
                CityNumber: '',
                CountyNumber: '',
                TownNumber: '',
                VillageNumber: '',
                Located: '',
                Planting_Area: '',
                Category_SerialNumber: '',
                Land_Certificate: '',
                value1: [],
                town: [],//市区
                value2: [],
            })
        },
        remove_land() {
            if (this.land.filter(item => item.Row_Status != '1').length > 1) {//必须至少剩1个
                let i = this.land.filter(item => item.Row_Status != '1').length - 1
                let obj = this.land.filter(item => item.Row_Status != '1')[i]
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    this.land.pop()
                } else {
                    this.$confirm('该操作将删除此土地信息,是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        this.land.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
                    }).catch(() => {
                        this.$message({
                            type: 'warning',
                            message: '已取消删除'
                        });
                    });
                }
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        submitForm(formName) {
            const that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true;
                    that.form.TownJSON = JSON.stringify(that.form.town);
                    let business_traceability_farmer = deepClone(that.form);
                    delete business_traceability_farmer.value1;
                    delete business_traceability_farmer.town;//市区
                    delete business_traceability_farmer.value2;
                    delete business_traceability_farmer.ID_Front;
                    delete business_traceability_farmer.ID_Front_Original;
                    that.land.forEach(item => {
                        // item.TownJSON = JSON.stringify(item.town);
                        item.TownJSON = "";
                    })
                    const { add, modify } = that.deal();
                    if (add == null) {
                        data = {//, business_traceability_land:modify 
                            Data: JSON.stringify({ Modify: { business_traceability_farmer } })
                        }
                    } else {
                        data = {
                            Data: JSON.stringify({ Add: { business_traceability_land: add }, Modify: { business_traceability_farmer, business_traceability_land: modify } })
                        }
                    }
                    console.log(JSON.parse(data.Data));
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                        type: 'POST',
                        data,
                        success: function (res) {
                            if (res.Status === 'success') {
                                that.$message.success("提交成功")
                                window.history.go(-1)
                            } else {
                                that.$message.error("提交失败，请稍后再试")
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    })
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            });
        },
        deal() {
            let add = [], modify = [];
            for (const i in this.land) {
                const obj = this.land[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add.push(obj)
                } else {
                    modify.push(obj)
                }
            }
            if (add.length == 0) {
                return { add: null, modify };
            }
            return { add, modify };
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    }
})